package belf.migrate.engine.job.structure.helper;

import belf.migrate.api.common.DatabaseCompatibility;
import belf.migrate.api.common.DatabaseIdentifier;
import belf.migrate.api.exception.CatalogException;
import belf.migrate.api.exception.DDLException;
import belf.migrate.api.model.QualifiersModel;
import belf.migrate.api.table.schema.Catalog;
import belf.migrate.api.table.schema.TablePath;
import belf.migrate.api.table.schema.UserDefType;
import belf.migrate.api.taskconf.JobContext;
import belf.migrate.api.type.DbObjectType;
import belf.migrate.api.type.LogLevelType;
import belf.migrate.api.util.EngineConf;
import belf.migrate.api.util.PostLog;
import belf.migrate.core.exception.BelfRuntimeException;
import belf.migrate.engine.ddl.BaseDDLConvert;
import belf.migrate.engine.ddl.type.TypeConvertFactory;
import belf.migrate.api.job.Job;
import belf.migrate.engine.job.JobResult;
import belf.migrate.engine.job.JobResultItem;
import belf.migrate.api.taskconf.Task;
import belf.migrate.api.util.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.List;

import static belf.migrate.api.job.JobCode.*;

/**
 * 同步源端数据库的自定义类型到目标端数据库
 */
@Slf4j
public class CreateTypeTool extends SqlTransformTool {
    public CreateTypeTool(Job job) {
        super(job);
    }

    public CreateTypeTool(Job job, JobContext jobContext) {
        super(job, jobContext);
    }

    @Override
    public JobResult run() {
        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "创建TYPE开始！",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        JobResult jobResult = new JobResult(SUCCESS, "创建选中的TYPE成功");
        Catalog sourceCatalog = jobContext.getSourceCatalog();
        Catalog sinkCatalog = jobContext.getSinkCatalog();
        String sourceSchema = jobContext.getTaskConf().getSourceConf().getSchemaName();

        QualifiersModel qualifiersModel = getSinkQualifiersModel();

        List<String> typeNames = job.getMissions(); //用户是否指定了要创建的TYPE的名字？
        try {
            List userDefTypes = sourceCatalog.listTypes(sourceSchema, typeNames);
            if (!CollectionUtils.isEmpty(userDefTypes)) {
                transform(userDefTypes, jobResult);
            }
        } catch (CatalogException e) {
            e.printStackTrace();
        }
        if (jobResult.getFailtures() > 0) {
            jobResult.setCode(CREATE_TYPE_ERROR);
            jobResult.setMessage("创建选中的TYPE失败");
            log.error("Create Some Types Of {} Failed.", jobContext.getValidSinkDatabase());
        } else {
            log.info("Create All Types Of {} Successfully.", jobContext.getValidSinkDatabase());
        }

        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                "创建TYPE结束！",
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        return jobResult;
    }

    @Override
    protected JobResultItem process(Object object) {
        UserDefType userDefType = (UserDefType)object;
        Catalog sinkCatalog = jobContext.getSinkCatalog();
        QualifiersModel qualifiersModel = getSinkQualifiersModel();
        String startTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        TablePath targetPath = TablePath.of(jobContext.getTaskConf().getSinkConf().getDatabaseName(),
                jobContext.getTaskConf().getSinkConf().getSchemaName(),
                userDefType.getTypeName(),
                qualifiersModel);

        JobResultItem jobResultItem = new JobResultItem(userDefType.getTypeName(), targetPath.getCaseTableName(), SUCCESS, "创建TYPE " + userDefType.getTypeName() + "成功");
        jobResultItem.setStartTime(startTime);
        jobResultItem.setType(DbObjectType.TYPE.getTypeName());

        String sourceDdl = "";
        String promptTempalate = """
                    请将以下%s创建触发器的SQL语句转为%s创建触发器的SQL语句：\n
                    %s\n
                    %s
                    """;
        String srcDbCatalog = DatabaseIdentifier.name(jobContext.getTaskConf().getSourceConf().getCatalogName());
        String targetDbCatalog = DatabaseIdentifier.name(jobContext.getTaskConf().getSinkConf().getCatalogName());
        String requirement = PromtHelper.requirement(jobContext.getTaskConf().getSourceConf().getCatalogName(),
                jobContext.getTaskConf().getSinkConf().getCatalogName(),
                jobContext.getTaskConf().getSinkConf().getSchemaName(),
                getSinkQualifiersModel(),
                DbObjectType.TYPE);

        String sinkDDL = null;
        SqlResponse sqlResponse = null;
        try {
            sourceDdl = userDefType.getDdl();
            //是否启用数据库的语法兼容性？比如达梦极大兼容Oracle
            boolean dbCompatible = EngineConf.getInstance().getBoolean("llm.enable.db.compatible");
            String prompt = String.format(promptTempalate,
                    srcDbCatalog,
                    dbCompatible? DatabaseCompatibility.name(sinkCatalog.name()):targetDbCatalog,
                    sourceDdl,
                    requirement);
            log.info("转换触发器的提示词：\n{}", prompt);

            sqlResponse = SqlAgent.post(jobContext.getTaskConf().getAiModel(), prompt);
            if (null != sqlResponse) {
                sinkDDL = sqlResponse.getSql();
                jobContext.getSinkCatalog().executeDdl(targetPath, sinkDDL);
                jobResultItem.setSinkDdl(sinkDDL);
                log.info("Create Trigger successfully:\n{}", sinkDDL);
            }
        } catch (DDLException e) {
            String endTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
            log.error("Type create error: \n{}", sinkDDL);
            e.printStackTrace();
            PostLog.sendLogModel(
                    job.getJobId(),
                    job.getTask().getTaskType().getName(),
                    String.format("创建类型 %s 失败", userDefType.getTypeName()),
                    LogLevelType.ERROR.getType(),
                    EXECUTING,
                    jobContext.getProgress());
            String errorTips = null;
            if (sqlResponse != null) {
                // 返回大模型给出的sql转化理由
                errorTips = String.join("\n", sqlResponse.getReasons());
            }
            return new JobResultItem(userDefType.getTypeName(),
                    targetPath.getCaseTableName(),
                    CREATE_TYPE_ERROR,
                    String.format("创建类型 %s 失败, SQL错误：%s", userDefType.getTypeName(), e.getCause().getMessage()),
                    ExceptionUtils.toString(e.getCause()),
                    DbObjectType.TYPE.getTypeName(),
                    startTime,
                    endTime,
                    userDefType.getDdl(),
                    sinkDDL,
                    errorTips);
        }

        PostLog.sendLogModel(
                job.getJobId(),
                job.getTask().getTaskType().getName(),
                String.format("创建类型 %s 成功", userDefType.getTypeName()),
                LogLevelType.INFO.getType(),
                EXECUTING,
                jobContext.getProgress());
        jobResultItem.setEndTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        return jobResultItem;
    }
}
